//
//  HttpsTools.swift
//  Bocai
//
//  Created by GujyHy on 2017/11/7.
//  Copyright © 2017年 GujyHy. All rights reserved.
//

import UIKit
import SwiftyJSON
import Alamofire
import SVProgressHUD

enum MethodType {
    case get
    case post
}


class HttpsTools: NSObject {
    
    //MARK:-网络请求管理
    static fileprivate var requestCacheArr = [DataRequest]();
    
    // 没有的话就会给出警告。如果你不想要这个警告，可以自己手动加上  @discardableResult ，如：
    @discardableResult
    class func requestData(_ type:MethodType,
                           URLString:String,
                           parameters:[String : Any]? = nil,
                           finishedCallBack:@escaping (_ json: JSON) ->(),
                           finishedFailure: @escaping (_ errorMessage:String) -> ()
        ) -> DataRequest {
        let method:HTTPMethod = type == .get ? HTTPMethod.get : HTTPMethod.post
        return self.defaultManager.request(URLString, method: method, parameters: parameters).responseJSON(completionHandler: {
            (response) in
            
            if let result = response.result.value {
                var json = JSON(result)
//                let code =  json["head"]["code"].stringValue
           
                finishedCallBack(json)
                
            }else{
                print(response.result)
                let error:NSError = response.result.error! as NSError
                print(error.code)
                print(response.result.error.debugDescription)
                if error.code != -999 { //
                    finishedFailure("网络请求异常") // 提示文字传过去
                }else{
                    finishedFailure("")
                }
            }
            
        })
        
        //记录网络请求
        //        self.requestCacheArr.append(dataRequest);
        //        return dataRequest
    }
    class func requestResponseData(_ type : MethodType,
                                   URLString : String,
                                   parameters :[String : Any]? = nil,
                                   headers:[String : String]? = nil,
                                   finishedCallBack : @escaping (_ result : Any) ->(),
                                   finishedFailure: @escaping (() -> ())
        ){
        //移除已经完成的网络请求
        //        self.removeTaks()
        let method:HTTPMethod = type == .get ? HTTPMethod.get : HTTPMethod.post
        self.defaultManager.request(URLString, method: method, parameters: parameters, encoding: URLEncoding.default, headers: headers).responseData {(responseData) in
            guard let result = responseData.data else{
                debugPrint(responseData.error as Any)
                return
            }
            finishedCallBack(result)
            
        }
    }
    
    // 没有的话就会给出警告。如果你不想要这个警告，可以自己手动加上  @discardableResult ，如：
    @discardableResult
    class func requestUpdateFirim(_ type:MethodType,
                                  URLString:String,
                                  parameters:[String : Any]? = nil,
                                  finishedCallBack:@escaping (_ json: JSON) ->(),
                                  finishedFailure: @escaping (_ errorMessage:String) -> ()
        ) -> DataRequest {
        
        let method:HTTPMethod = type == .get ? HTTPMethod.get : HTTPMethod.post
        return self.defaultManager.request(URLString, method: method, parameters: parameters).responseJSON(completionHandler: {
            (response) in
            
            if let result = response.result.value {
                let json = JSON(result)
                finishedCallBack(json)
                
            }else{
                print(response.result)
                let error:NSError = response.result.error! as NSError
                print(error.code)
                print(response.result.error.debugDescription)
                if error.code != -999 { //
                    finishedFailure("网络请求异常") // 提示文字传过去
                }else{
                    finishedFailure("")
                }
            }
            
        })
        
    }
    
    open static let `defaultManager`: SessionManager = {
        let configuration = URLSessionConfiguration.default
        var httpHeaders = SessionManager.defaultHTTPHeaders
        httpHeaders["platform"] = "iOS"
        configuration.httpAdditionalHeaders = httpHeaders
 
        configuration.timeoutIntervalForRequest = 15 // seconds
        configuration.timeoutIntervalForResource = 15
        return SessionManager(configuration: configuration)
    }()
    
    
    
}
